package cn.edu.scnu.user.controller;

import cn.edu.scnu.annotation.IgnoreToken;
import cn.edu.scnu.pojo.Organizer;
import cn.edu.scnu.pojo.User;
import cn.edu.scnu.user.service.OrgService;
import cn.edu.scnu.vo.OrganizerVO;
import cn.edu.scnu.vo.ResultCode;
import cn.edu.scnu.vo.SysResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@Api
@RestController
public class OrgController {
    @Autowired
    private OrgService orgService;

    @PutMapping("/orgs")
    @ApiOperation("修改用户信息")
    @ApiImplicitParam(
            name = "user",
            value = "用户信息",
            dataType = "cn.edu.scnu.pojo.PersonalUser",
            required = true,
            type = "body"
    )
    public SysResult saveOrg(@RequestBody Organizer user) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user1 = (User) authentication.getPrincipal();
        if (!user.getUsername().equals(user1.getUsername())) {
            return SysResult.build(ResultCode.FORBIDDEN, "权限错误", null);
        }
        orgService.saveOrg(user);
        return SysResult.build(ResultCode.CREATED, "update success", user);
    }

    @IgnoreToken
    @GetMapping("/orgs/{username}")
    @ApiOperation("查看用户信息")
    @ApiImplicitParam(
            name = "username",
            value = "用户名",
            dataType = "String",
            required = true,
            type = "path"
    )
    public SysResult getOrgByUname(@PathVariable String username) {
        OrganizerVO org = orgService.getOrgByUname(username);
        if (org != null) {
            return SysResult.build(ResultCode.SUCCESS, "success", org);
        }
        return SysResult.build(ResultCode.NOT_FOUND, "not found", null);
    }

    //    @IgnoreToken
//    @GetMapping("/orgs/{username}/matchs")
//    @ApiOperation("获取组织举办的比赛")
//    public SysResult getAllMatchByUname(@PathVariable String username) {
//        return SysResult.build(ResultCode.NOT_FOUND, "not found", null);
//    }
    @IgnoreToken
    @GetMapping("/orgs/id/{userId}")
    @ApiOperation("查看用户信息")
    @ApiImplicitParam(
            name = "userId",
            value = "用户名",
            dataType = "String",
            required = true,
            type = "path"
    )
    public SysResult getOrgById(@PathVariable String userId) {
        OrganizerVO org = orgService.getOrgById(userId);
        if (org != null) {
            return SysResult.build(ResultCode.SUCCESS, "success", org);
        }
        return SysResult.build(ResultCode.NOT_FOUND, "not found", null);
    }
}
